 //Socket.hpp
 #pragma once
 #include<iostream>
 #include<unistd.h>
 #include<sys/socket.h>
 #include<sys/types.h>
 #include<arpa/inet.h>
 #include<cstring>
 #include<cstdlib>
 //封装套接字的创建、绑定和监听
class Socket{
public:
    static int SocCreate()//创建套接字
    {
        int sockFd=socket(AF_INET,SOCK_STREAM,0);
        if(sockFd<0)
        {
            std::cerr<<"socket error"<<std::endl;
            exit(2);
        }
        //确保服务器在关闭后立即重新启动，而不会因为地址仍在使用中（由于TIME_WAIT状态）而失败。
        int opt=1;//标志位，开启或者关闭
        setsockopt(sockFd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
        return sockFd;
    }
    static void SocketBind(int sockFd,int port)//绑定套接字
    {
        struct sockaddr_in local;
        memset(&local,0,sizeof(local));
        local.sin_family=AF_INET;
        local.sin_port=htons(port);
        local.sin_addr.s_addr=INADDR_ANY;
        
        socklen_t len=sizeof(local);

        if(bind(sockFd,(struct sockaddr*)&local,len))
        {
            std::cerr<<"bind error"<<std::endl;
            exit(3);
        }
    }
    
    static void SocketListen(int sockFd,int backlog)//监听套接字
    {
        if(listen(sockFd,backlog)<0)
        {
            std::cerr<<"listen error"<<std::endl;
            exit(4);
        }
    }

};
